/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.star.admin.controller;

import com.star.common.ActionType;
import com.star.common.CateData;
import com.star.common.CommonUtil;
import com.star.common.ConfigFactory;
import com.star.common.PostData;
import com.star.common.ProfileData;
import com.star.common.Re_Post_Profile_Data;
import com.star.common.RenderModel;
import com.star.common.UserData;
import com.star.common.UserRole;
import com.start.model.ActionModel;
import com.start.model.CateModel;
import com.start.model.PostModel;
import com.start.model.ProfileModel;
import com.start.model.Re_Post_Profile_Model;
import com.start.model.SessionModel;
import com.start.model.UserModel;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javaxt.io.Image;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

/**
 *
 * @author ngotandieu
 */
public class AdminProfileController extends HttpServlet {

    private static final Logger logger = Logger.getLogger(AdminProfileController.class);
    private static final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    //private static final int POST_PER_PAGE = 100;

    public static final String STATIC_UPLOAD_AVATAR = ConfigFactory.getParam("upload", "upload_path") + ConfigFactory.getParam("upload", "upload_avatar");
    public static final String STATIC_URL_AVATAR = ConfigFactory.getParam("static", "img") + ConfigFactory.getParam("upload", "upload_avatar");

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            if (!CommonUtil.checkSession(req, resp)) {
                return;
            }
            processs(req, resp);
        } catch (IOException ex) {
            logger.error("AdminPostController.handle:" + ex.getMessage(), ex);
        }
    }

    private void processs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content;
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        switch (pathInfo) {
            case "/edit":
                content = renderEditPage(req, resp);
                break;
            case "/ajax-edit-profile":
                content = ajaxEdit(req, resp);
                break;
            case "/ajax-delete-profile":
                content = ajaxDelete(req, resp);
                break;    
            case "/add":
                content = renderAddPage(req, resp);
                break;
            case "/ajax-add-profile":
                content = ajaxAdd(req, resp);
                break;            
            case "/search":
                content = renderSearchPage(req, resp);
                break; 
            default:
                content = renderIndexPage(req, resp);
        }
        CommonUtil.out(content, resp);
    }

    private String renderIndexPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.PROFILE_VIEW) && !CommonUtil.checkAccess(req, UserRole.PROFILE_EDIT)) {
                resp.sendRedirect("/");
                return "";
            }

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "profile_list"));
            dic.setVariable("PAGE_TITLE", "Danh sách profile");

//            int page = 1;
//            String p = req.getParameter("p") == null ? "1" : req.getParameter("p");
//            try {
//                page = Integer.parseInt(p);
//            } catch (NumberFormatException e) {
//            }

            ProfileModel appsModel = ProfileModel.getInstance();
            List<ProfileData> lstProfile = appsModel.getProfile(0, -1);
            
            if (lstProfile != null) {
                String firstChart = "";
                TemplateDataDictionary proList = TemplateDictionary.create();
                TemplateDataDictionary proSection = null;
                for (ProfileData profileData : lstProfile) {
                    //String f = profileData.getName().substring(0, 1);
                    String f = profileData.getSlug().substring(0, 1);
                    if(!firstChart.equalsIgnoreCase(f)) {
                        firstChart = f;
                        proSection = proList.addSection("PROFILE_SECTION");
                        proSection.setVariable("PROFILE_SECTION_NAME", f);
                    }
                    TemplateDataDictionary section = proSection.addSection("PROFILE_LIST");
                    String icon = profileData.getAvatar();
                    icon = icon.equalsIgnoreCase("") ? "/upload/avatar/defavatar.jpg" : STATIC_URL_AVATAR + icon;
                    section.setVariable("PROFILE_ID", String.valueOf(profileData.getId()));
                    section.setVariable("PROFILE_AVATAR", icon);
                    section.setVariable("PROFILE_NAME", profileData.getName());
                    section.setVariable("PROFILE_REALNAME", profileData.getRealname());
                }
                Template template = RenderModel.getAdminCTemplate("profile_list_data");
                String proListData = template.renderToString(proList);
                dic.setVariable("PROFILE_LIST_DATA", proListData);
            }

            //long count = appsModel.getProfileCount();
            //String requestURI = req.getRequestURI() + (req.getQueryString() != null ? "?" + req.getQueryString() : "");
            //String pageNavi = CommonUtil.getPageNavi(page, (int) count, POST_PER_PAGE, requestURI);
            //dic.setVariable("PAGENAVI", pageNavi);

            
            UserModel userModel = UserModel.getInstance();
            List<UserData> userList = userModel.getUser(0, -1);
            for (UserData userData : userList) {
                TemplateDataDictionary section = dic.addSection("USER_LIST");
                section.setVariable("USER_ID", userData.getId());
                section.setVariable("USER_NAME", userData.getUsername());                
            }
            
            
            // Get category
            CateModel cateModel = CateModel.getInstance();
            List<CateData> listCate = cateModel.getCate(0, -1);
            if (listCate != null && !listCate.isEmpty()) {
                for (CateData cateData : listCate) {
                    TemplateDataDictionary section = dic.addSection("CATE_LIST");
                    section.setVariable("CATE_ID", String.valueOf(cateData.getId()));
                    section.setVariable("CATE_NAME", cateData.getName());
                }
            }

            Template template = RenderModel.getAdminCTemplate("profile_list");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminProfileController.renderIndexPage: " + ex.getMessage(), ex);
        }
        return content;
    }
    
    
    
    private String renderSearchPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.PROFILE_VIEW) && !CommonUtil.checkAccess(req, UserRole.PROFILE_EDIT)) {
                return CommonUtil.toPermissionDenied();
            }

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "profile_list"));
            dic.setVariable("PAGE_TITLE", "Danh sách profile");
                                  
            String sortProfile = req.getParameter("postSort") != null ? req.getParameter("postSort") : "";            
            String id_Search = req.getParameter("postID") != null ? req.getParameter("postID") : "";
            String user = req.getParameter("postUser") != null ? req.getParameter("postUser") : "";
            String nameProfile = req.getParameter("postNameProfile") != null ? req.getParameter("postNameProfile") : "";
            String cate = req.getParameter("postCate") != null ? req.getParameter("postCate") : "";
            String created = req.getParameter("postCreated") != null ? req.getParameter("postCreated") : "";            
            String userSearch = "";
            if(!user.equals("")){
                UserModel userModelSearch = UserModel.getInstance();
                UserData userDataSearch = userModelSearch.getUserById(user);
                userSearch = userDataSearch.getUsername();
            }
            
            ProfileModel appsModel = ProfileModel.getInstance();   
            List<ProfileData> lstProfile = appsModel.getProfile(0, -1, id_Search, userSearch, 
                    nameProfile, created, cate, sortProfile);            
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
            if (lstProfile != null && !lstProfile.isEmpty()) {
                String firstChart = "";
                TemplateDataDictionary proList = TemplateDictionary.create();
                TemplateDataDictionary proSection = null;
                for (ProfileData profileData : lstProfile) {                    
                    String f = profileData.getSlug().substring(0, 1);
                    if(!firstChart.equalsIgnoreCase(f)) {
                        firstChart = f;
                        proSection = proList.addSection("PROFILE_SECTION");
                        proSection.setVariable("PROFILE_SECTION_NAME", f);
                    }
                    TemplateDataDictionary section = proSection.addSection("PROFILE_LIST");
                    String icon = profileData.getAvatar();
                    icon = icon.equalsIgnoreCase("") ? "/upload/avatar/defavatar.jpg" : STATIC_URL_AVATAR + icon;
                    section.setVariable("PROFILE_ID", String.valueOf(profileData.getId()));
                    section.setVariable("PROFILE_AVATAR", icon);
                    section.setVariable("PROFILE_NAME", profileData.getName());
                    section.setVariable("PROFILE_REALNAME", profileData.getRealname());
                }
                Template template = RenderModel.getAdminCTemplate("profile_list_data");
                String proListData = template.renderToString(proList);
                dic.setVariable("PROFILE_LIST_DATA", proListData);
            }
            
            UserModel userModel = UserModel.getInstance();
            List<UserData> userList = userModel.getUser(0, -1);
            for (UserData userData : userList) {
                TemplateDataDictionary section = dic.addSection("USER_LIST");
                section.setVariable("USER_ID", userData.getId());
                section.setVariable("USER_NAME", userData.getUsername()); 
                if(user.equals(userData.getId()))
                    section.showSection("USER_SELECTED");
            }

            // Get category
            CateModel cateModel = CateModel.getInstance();
            List<CateData> listCate = cateModel.getCate(0, -1);
            if (listCate != null && !listCate.isEmpty()) {
                for (CateData cateData : listCate) {
                    TemplateDataDictionary section = dic.addSection("CATE_LIST");
                    section.setVariable("CATE_ID", String.valueOf(cateData.getId()));
                    section.setVariable("CATE_NAME", cateData.getName());
                    if(cate.equals(cateData.getId()))
                        section.showSection("CATE_SELECTED");
                }
            }
                 
            dic.setVariable("ID_SEARCH", id_Search);
            dic.setVariable("NAME_PROFILE_SEARCH", nameProfile);
            dic.setVariable("CREATE_SEARCH", created);            
            if (sortProfile.equals("az")) 
                dic.showSection("SORT_AZ");            
            else if (sortProfile.equals("za"))
                dic.showSection("SORT_ZA");            
            
            Template template = RenderModel.getAdminCTemplate("profile_list");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminProfileController.renderSearchPage: " + ex.getMessage(), ex);
        }
        return content;
    }
    
    

    private String renderAddPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.PROFILE_ADD)) {
                resp.sendRedirect("/");
                return "";
            }

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "profile_add"));
            dic.setVariable("PAGE_TITLE", "Thêm mới");

            CateModel cateModel = CateModel.getInstance();
            List<CateData> listCate = cateModel.getCate(0, -1);
            if (listCate != null && !listCate.isEmpty()) {
                for (CateData cateData : listCate) {
                    TemplateDataDictionary section = dic.addSection("CATE_LIST");
                    section.setVariable("CATE_ID", String.valueOf(cateData.getId()));
                    section.setVariable("CATE_NAME", cateData.getName());
                }
            }
            Template template = RenderModel.getAdminCTemplate("profile_add");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminProfileController.renderAddPage: " + ex.getMessage(), ex);
        }
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
        return content;
    }

    private String ajaxAdd(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.checkAccess(req, UserRole.PROFILE_ADD)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Thêm post thành công.";
        Map<String, String> data = new HashMap<>();
        try {
            String profileName = "";
            String profileRealName = "";
            long profileDOB = 0;
            String profileCountry = "";
            String profileAvatar = "";
            String profileContent = "";
            FileItem fileAvatar = null;
            List<String> lstCats = new ArrayList<>();

            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(req);

            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                String name = item.getFieldName();
                if (item.isFormField()) {
                    String value = item.getString("UTF-8");
                    switch (name) {
                        case "profileName":
                            profileName = value;
                            break;
                        case "profileRealName":
                            profileRealName = value;
                            break;
                        case "profileDOB":
                            if (!value.isEmpty()) {
                                Date date = formatter.parse(value);
                                profileDOB = date.getTime();
                            }
                            break;
                        case "profileCountry":
                            profileCountry = value;
                            break;
                        case "profileContent":
                            profileContent = value;
                            break;
                        case "profileCate":
                            lstCats.add(value);
                            break;
                    }
                } else {
                    if (name.equalsIgnoreCase("profileAvatar")) {
                        String fileName = item.getName();
                        String contentType = item.getContentType();
                        if (!contentType.startsWith("image/")) {
                            msg = "Chỉ được phép upload hình jpg, png, gif.";
                            error = -1;
                        }
                        long sizeInBytes = item.getSize();
                        if (sizeInBytes > 1024 * 1000) {
                            msg = "Kích thước tối đa 1 MB.";
                            error = -1;
                        }
                        profileAvatar = (System.currentTimeMillis() / 1000) + "_" + fileName.toLowerCase();
                        profileAvatar = profileAvatar.substring(0, profileAvatar.length() - 4) + ".jpg";
                        fileAvatar = item;
                    }
                }
            }
            if (profileName.equalsIgnoreCase("")) {
                msg = "Họ tên không được trống.";
                error = -1;
            }
            if (error == 0) {
                SessionModel sessionModel = SessionModel.getInstance();
                ProfileModel profileModel = ProfileModel.getInstance();
                String author = sessionModel.getUserLogin(req);
                
                ProfileData postData = new ProfileData(profileName, profileRealName, profileAvatar, profileDOB, 
                        profileCountry, profileContent, lstCats, author);

                String profileId = profileModel.addProfile(postData);
                if (profileId.equalsIgnoreCase("")) {
                    msg = "Tạo post thất bại";
                    error = -1;
                } else {
                    data.put("id", String.valueOf(profileId));
                    saveThumb(fileAvatar, profileAvatar);
                    if (!lstCats.isEmpty()) {
                        CateModel cateModel = CateModel.getInstance();
                        boolean setProfileForCate = cateModel.setProfileForCate(profileId, lstCats);
                        if (!setProfileForCate) {
                            msg = "Tạo danh mục thất bại";
                            error = -1;
                        }
                    }
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, author, ActionType.PROFILE_ADD, profileId, profileName);
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg, data);
        return content;
    }

    private String renderEditPage(HttpServletRequest req, HttpServletResponse resp) {        
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.PROFILE_VIEW) && !CommonUtil.checkAccess(req, UserRole.PROFILE_EDIT)) {
                resp.sendRedirect("/");
                return "";
            }
            
            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "profile_edit"));
            dic.setVariable("PAGE_TITLE", "Tiểu sử");

            String id = req.getParameter("id") != null ? req.getParameter("id") : "";
            if (id.equalsIgnoreCase("")) {
                resp.sendRedirect("/profile");
                return "";
            }

            ProfileModel profileModel = ProfileModel.getInstance();
            ProfileData profileData = profileModel.getProfileById(id);
            if (profileData != null) {
                dic.setVariable("PROFILE_ID", profileData.getId());
                dic.setVariable("PROFILE_NAME", profileData.getName());
                dic.setVariable("PROFILE_REALNAME", profileData.getRealname());
                String dob = profileData.getDob() == 0 ? "" : formatter.format(profileData.getDob());
                dic.setVariable("PROFILE_DOB", dob);
                dic.setVariable("PROFILE_COUNTRY", profileData.getCountry());
                dic.setVariable("PROFILE_CONTENT", profileData.getProfile());

                String avatar = profileData.getAvatar();
                if (avatar.isEmpty()) {
                    dic.showSection("NO_THUMB");
                } else {
                    dic.showSection("HAS_THUMB");
                    dic.setVariable("PROFILE_AVATAR", STATIC_URL_AVATAR + avatar);
                    dic.setVariable("PROFILE_AVATAR_NAME", avatar);
                }
                String updated = formatter.format(profileData.getUpdated());
                String created = formatter.format(profileData.getCreated());
                dic.setVariable("PROFILE_UPDATED", updated);
                dic.setVariable("PROFILE_EDITOR", profileData.getEditor());
                dic.setVariable("PROFILE_AUTHOR", profileData.getAuthor());
                dic.setVariable("PROFILE_CREATED", created);

                List<String> cates = profileData.getCates();

                CateModel cateModel = CateModel.getInstance();
                List<CateData> listCate = cateModel.getCate(0, -1);
                if (listCate != null && !listCate.isEmpty()) {
                    for (CateData cateData : listCate) {
                        TemplateDataDictionary section = dic.addSection("CATE_LIST");
                        section.setVariable("CATE_ID", String.valueOf(cateData.getId()));
                        section.setVariable("CATE_NAME", cateData.getName());
                        if (cates.contains(cateData.getId())) {
                            section.showSection("CATE_CHECKED");
                        }
                    }
                }

                TemplateDataDictionary postDic = TemplateDictionary.create();
                postDic.setVariable("PROFILE_ID", id);               
                if(CommonUtil.checkAccess(req, UserRole.POST_VIEW) || CommonUtil.checkAccess(req, UserRole.POST_EDIT)){
                    PostModel postModel = PostModel.getInstance();
                    Re_Post_Profile_Model reModel = Re_Post_Profile_Model.getInstance();
                    List<Re_Post_Profile_Data> listData = reModel.getItemsByProfileId(id);
                    for(Re_Post_Profile_Data item : listData){
                        PostData postData = postModel.getPostById(item.getIdPost());
                        TemplateDataDictionary addSection = postDic.addSection("POST_LIST");
                        addSection.setVariable("POST_ID", postData.getId());
                        addSection.setVariable("POST_TITLE", postData.getTitle());
                        String time = formatter.format(postData.getPublished());
                        addSection.setVariable("POST_TIME", time);
                    }      
                }
                
                if (CommonUtil.checkAccess(req, UserRole.POST_ADD)) {
                    postDic.showSection("POST_ADD");
                }
                Template postTemplate = RenderModel.getAdminCTemplate("profile_news");
                dic.setVariable("PROFILE_NEWS", postTemplate.renderToString(postDic));

                if (CommonUtil.checkAccess(req, UserRole.PROFILE_EDIT)) {
                    dic.showSection("PROFILE_EDIT");
                }
                Template template = RenderModel.getAdminCTemplate("profile_edit");
                content = template.renderToString(dic);
            } else {
                resp.sendRedirect("/profile");
                return "";
            }
        } catch (Exception ex) {
            logger.error("AppsController.renderAddPage: " + ex.getMessage(), ex);
        }
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
        return content;
    }

    private String ajaxEdit(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.checkAccess(req, UserRole.PROFILE_EDIT)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Cập nhật thành công.";
        Map<String, String> data = new HashMap<>();
        try {
            String profileId = "";
            String profileName = "";
            String profileRealName = "";
            long profileDOB = 0;
            String profileCountry = "";
            String profileAvatar = "";
            String profileAvatarOld = "";
            String profileContent = "";
            FileItem fileAvatar = null;
            List<String> lstCats = new ArrayList<>();

            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(req);

            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                String name = item.getFieldName();
                if (item.isFormField()) {
                    String value = item.getString("UTF-8");
                    switch (name) {
                        case "profileId":
                            profileId = value;
                            break;
                        case "profileName":
                            profileName = value;
                            break;
                        case "profileRealName":
                            profileRealName = value;
                            break;
                        case "profileDOB":
                            if (!value.isEmpty()) {
                                Date date = formatter.parse(value);
                                profileDOB = date.getTime();
                            }
                            break;
                        case "profileCountry":
                            profileCountry = value;
                            break;
                        case "profileContent":
                            profileContent = value;
                            break;
                        case "profileAvatarOld":
                            profileAvatarOld = value;
                            break;
                        case "profileCate":
                            lstCats.add(value);
                            break;
                    }
                } else {
                    if (name.equalsIgnoreCase("profileAvatar")) {
                        String fileName = item.getName();
                        String contentType = item.getContentType();
                        if (!contentType.startsWith("image/")) {
                            msg = "Chỉ được phép upload hình jpg, png, gif.";
                            error = -1;
                        }
                        long sizeInBytes = item.getSize();
                        if (sizeInBytes > 1024 * 1000) {
                            msg = "Kích thước tối đa 1 MB.";
                            error = -1;
                        }
                        profileAvatar = (System.currentTimeMillis() / 1000) + "_" + fileName.toLowerCase();
                        profileAvatar = profileAvatar.substring(0, profileAvatar.length() - 4) + ".jpg";
                        fileAvatar = item;
                    }
                }
            }
            if (profileId.equalsIgnoreCase("")) {
                msg = "Id không hợp lệ.";
                error = -1;
            }
            if (profileName.equalsIgnoreCase("")) {
                msg = "Họ tên không được trống.";
                error = -1;
            }
            if (error == 0) {
                SessionModel sessionModel = SessionModel.getInstance();
                ProfileModel profileModel = ProfileModel.getInstance();
                ProfileData profileEdit = profileModel.getProfileById(profileId);
                String profileNameEdit = profileEdit.getName();
                String author = sessionModel.getUserLogin(req);
                profileAvatar = fileAvatar == null ? profileAvatarOld : profileAvatar;                
                
                
                                
                ProfileData profileData = new ProfileData(profileId, profileName, profileRealName, profileAvatar, 
                        profileDOB, profileCountry, profileContent, lstCats, author);

                boolean addApps = profileModel.updateProfile(profileData);
                if (!addApps) {
                    msg = "Cập nhật thất bại";
                    error = -1;
                } else {
                    data.put("id", String.valueOf(addApps));
                    saveThumb(fileAvatar, profileAvatar);
                    if (!lstCats.isEmpty()) {
                        CateModel cateModel = CateModel.getInstance();
                        boolean setProfileForCate = cateModel.setProfileForCate(profileId, lstCats);
                        if (!setProfileForCate) {
                            msg = "Tạo danh mục thất bại";
                            error = -1;
                        } 
                    }
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, author, ActionType.PROFILE_EDIT, profileId, profileNameEdit);
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg, data);
        return content;
    }

    private String ajaxDelete(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.checkAccess(req, UserRole.PROFILE_EDIT)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Xoá thành công.";
        try {
            String id = req.getParameter("id") != null ? req.getParameter("id") : "";
            String profileName = req.getParameter("name") != null ? req.getParameter("name") : "";
            if (id.equalsIgnoreCase("")) {
                msg = "Profile Id không hợp lệ.";
                error = -1;
            }

            if (error == 0) {
                ProfileModel profileModel = ProfileModel.getInstance();
                ProfileData profileData = profileModel.getProfileById(id);
                SessionModel sessionModel = SessionModel.getInstance();
                String author = sessionModel.getUserLogin(req);
                boolean profile = profileModel.deleteProfile(id);
                if (!profile) {
                    msg = "Có lỗi xảy ra.";
                    error = -1;
                } else {
                    deleteThumb(profileData.getAvatar());
                    
                    Re_Post_Profile_Model modelRe_Post_Profile = Re_Post_Profile_Model.getInstance();
                    modelRe_Post_Profile.deleteItemsByIdProfile(id);
                    
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, author, ActionType.PROFILE_DELETE, id, profileName);
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg);
        return content;
    }

    private void saveThumb(FileItem fileAvatar, String profileAvatar) throws Exception {
        if (fileAvatar != null) {
            Image image = new Image(fileAvatar.get());
            image.resize(150, 150);
            int w = image.getWidth() > 150 ? 150 : image.getWidth();
            int h = image.getHeight() > 150 ? 150 : image.getHeight();
            image.crop(0, 0, w, h);

            BufferedImage bi = CommonUtil.convertPNGToJPG(image.getBufferedImage());
            String localPath = STATIC_UPLOAD_AVATAR + profileAvatar;            
            
            File uploadedFile = new File(localPath);
            ImageIO.write(bi, "jpg", uploadedFile);
        }
    }

    private void deleteThumb(String thumb) {
        if (thumb == null || thumb.isEmpty()) {
            return;
        }
        String localPath = STATIC_UPLOAD_AVATAR + thumb;
        File file = new File(localPath);
        if (file.exists()) {
            file.delete();
            logger.info("Delete avatar success");
        }
    }
}
